<template>
  <div class="service-type-selector">
    <a-collapse v-model:activeKey="activeKey" collapsible="header">
      <template #expandIcon></template>
      <a-collapse-panel v-for="(serviceTypes, groupKey) in serviceTypesGroup" :key="groupKey">
        <template #header>
          <a-space style="width: 100%" @click="handleClick">
            <e-icon indicator :type="activeKey.indexOf(groupKey) > -1 ? 'Unfold' : 'Fold'" color="#818d9f" />
            <a-checkbox
              :disabled="serviceTypes[0].serviceGroup === 6"
              :checked="serviceTypes.every(serviceType => serviceType.checked)"
              :indeterminate="
                serviceTypes.some(serviceType => serviceType.checked) &&
                !serviceTypes.every(serviceType => serviceType.checked)
              "
              @change="handleGroupChange($event, groupKey)">
              {{ serviceTypes[0].serviceGroupName }}
            </a-checkbox>
          </a-space>
        </template>
        <a-row v-for="serviceType in serviceTypes" :key="serviceType.serviceType">
          <a-col :span="20" class="service-type-name">
            <a-checkbox
              v-model:checked="serviceType.checked"
              :disabled="serviceType.serviceGroup === 6"
              @change="handleItemChange($event, serviceType.serviceGroup)">
              {{ serviceType.serviceTypeName }}
            </a-checkbox>
          </a-col>
          <a-col :span="4" class="unit-name">{{ serviceType.unitName }}</a-col>
        </a-row>
      </a-collapse-panel>
    </a-collapse>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import ServicePrice from '@/api/client/servicePrice.js'
import { groupBy } from 'lodash-es'
import EIcon from '@/components/EIcon.vue'
const props = defineProps({
  currencyId: {
    type: Number
  },
  priceInfo: {
    type: Array,
    default() {
      return []
    }
  }
})
const serviceTypesGroup = ref([])
const activeKey = ref([])
const selectedServiceTypes = ref([])
ServicePrice.getAllServiceType().then(({ data }) => {
  serviceTypesGroup.value = groupBy(data, item => item.orderByID)
  if (Array.isArray(props.priceInfo) && props.priceInfo.length > 0) {
    // 从价格信息中使用关键变量序列化后作为主键
    selectedServiceTypes.value = Object.keys(
      groupBy(props.priceInfo, item => {
        const { serviceType, fileKind, workloadUnit, breakDown } = item
        return JSON.stringify({
          serviceType,
          fileKind,
          workloadUnit,
          breakDown
        })
      })
    )
    for (const key in serviceTypesGroup.value) {
      serviceTypesGroup.value[key].forEach(item => {
        const { serviceType, fileKind, workloadUnit, breakDown } = item
        // 选中已选择的项
        if (
          selectedServiceTypes.value.indexOf(JSON.stringify({ serviceType, fileKind, workloadUnit, breakDown })) > -1
        ) {
          item.checked = true
        }
      })
    }
  }
})
// 防止点击checkbox导致折叠
const handleClick = event => {
  if (event.target.getAttribute('indicator') === null && event.target.tagName !== 'DIV') {
    event.stopPropagation()
  }
}
// 选中第一分组中的项，则CAT一起选中
const handleGroupChange = (event, groupKey) => {
  serviceTypesGroup.value[groupKey].forEach(serviceType => (serviceType.checked = event.target.checked))
  if (groupKey === '1') checkCatOption()
}
// 选中第一分组中的项，则CAT一起选中
const handleItemChange = (event, groupKey) => {
  if (groupKey === 1) checkCatOption()
}
const checkCatOption = () => {
  if (serviceTypesGroup.value['1'].some(serviceType => serviceType.checked)) {
    serviceTypesGroup.value['2'].forEach(serviceType => (serviceType.checked = true))
  } else {
    serviceTypesGroup.value['2'].forEach(serviceType => (serviceType.checked = false))
  }
}
const getCheckedItem = () => {
  const items = []
  for (const groupKey in serviceTypesGroup.value) {
    serviceTypesGroup.value[groupKey].forEach(serviceType => {
      if (serviceType.checked) {
        items.push({
          serviceType: serviceType.serviceType,
          fileKind: serviceType.fileKind,
          unit: serviceType.workloadUnit,
          currency: props.currencyId,
          breakDown: serviceType.breakDown
        })
      }
    })
  }
  // 没有选中的项目
  if (items.length === 0) return false
  // 现在选中的不存在与原来选中的标记type为1，代表添加
  items.forEach(item => {
    const { serviceType, fileKind, unit, breakDown } = item
    const primaryKey = JSON.stringify({
      serviceType,
      fileKind,
      workloadUnit: unit,
      breakDown
    })
    if (selectedServiceTypes.value.indexOf(primaryKey) === -1) {
      item.type = 1
    }
  })
  // 原来选中的不在现在选中的项目中标记为type为2，代表删除
  selectedServiceTypes.value.forEach(selectedJsonString => {
    const selected = JSON.parse(selectedJsonString)
    const found = items.find(
      item =>
        item.serviceType === selected.serviceType &&
        item.fileKind === selected.fileKind &&
        item.unit === selected.workloadUnit &&
        item.breakDown === selected.breakDown
    )
    if (!found) {
      selected.currency = props.currencyId
      selected.type = 2
      selected.unit = selected.workloadUnit
      items.push(selected)
    }
  })
  // 返回被标记的项目
  return items.filter(item => typeof item.type !== 'undefined')
}
defineExpose({ getCheckedItem })
</script>

<style lang="less" scoped>
:deep(.ant-checkbox-disabled) {
  & + span {
    color: @black-85p;
  }
}
:deep(.ant-checkbox-checked) {
  & + span {
    color: @primary-color;
  }
}
.service-type-selector {
  :deep(.ant-collapse-header) {
    .ant-checkbox-wrapper {
      font-weight: bold;
      color: @text-gray;
    }
    .ant-checkbox-disabled + span {
      color: @text-gray;
    }
    .ant-checkbox-checked + span {
      color: @primary-color;
    }
  }
  :deep(.ant-collapse-content-box) {
    padding: 0;
    .service-type-name {
      padding: 16px 52px;
      border-bottom: 1px solid @gray;
    }
    .unit-name {
      padding: 16px 0;
      text-align: center;
      border-bottom: 1px solid @gray;
      border-left: 1px solid @gray;
    }
    .ant-row:last-child {
      .unit-name,
      .service-type-name {
        border-bottom: none;
      }
    }
  }
}
</style>
